#!/bin/bash

# 用于解析trace文件中kvm_exit到下一次kvm_entry的时间，用于虚拟机陷出时间分析
trace_file=$1
entry_time=0
exit_time=0
start_time=0
last_time=0
total_exit_time=0
max_exit_time=0
max_exit_line_num=0
# 计算$1-$2的时间差，单位：us
function cal_time {
	val1_s=`echo $1 | awk -F '.' '{print $1}'`
	val1_us=`echo $1 | awk -F '.' '{print $2}'`
	val1_us=$(echo $val1_s$val1_us)
	val2_s=`echo $2 |  awk -F '.' '{print $1}'`
	val2_us=`echo $2 | awk -F '.' '{print $2}'`
	val2_us=$(echo $val2_s$val2_us)
	result_us=$(($val1_us-$val2_us))
	echo $result_us
}

total_line_num=`cat $1 | wc -l`

mark=''
com_value=0
function show_working_stage {
	result=`awk 'BEGIN{printf "%.0f\n",('$1'/'$total_line_num')*100}'`
	if [ $result -gt $com_value ]
	then
		com_value=$(($com_value+5))
		printf "progress:[%-40s]%d%%\r" "${mark}" "${com_value}"
		mark="##${mark}"
	fi
}

line_num=0
while read line
do
	line_num=`expr $line_num + 1`
	#echo $line_num
	show_working_stage $line_num
	event_name=`echo $line | awk -F ':' '{print $2}' | awk '{gsub(/ /,"")}1'`
	if [ -n $event_name ] && [ "$event_name" = "kvm_entry" ]
	then
		entry_time=`echo $line | awk '{print $5}' | awk -F ':' '{print $1}'`
		#echo "entry_time: "$entry_time
		if [ $exit_time = 0 ]
		then
			continue #如果kvm_entry先出现，直接continue
		else
			exit_during_us=$(cal_time $entry_time $exit_time) # exit-entry时间计算虚拟机陷出时间
			#echo "exit_during_us: "$exit_during_us
			total_exit_time=$(expr $total_exit_time + $exit_during_us)
			if [ $exit_during_us -gt $max_exit_time ]
			then
				max_exit_time=$exit_during_us
				max_exit_line_num=$line_num

			fi
			last_time=$entry_time
		fi
	fi

	if [ "$event_name" = "kvm_exit" ]
	then
		exit_time=`echo $line | awk '{print $5}' | awk -F ':' '{print $1}'`
		#echo "exit_time: "$exit_time
		if [ $start_time = 0 ]
		then
			start_time=$exit_time # 以kvm_exit首次出现的时间点作为start time
		fi
	fi
done < $trace_file

total_time=$(cal_time $last_time $start_time)
printf "\n------result----------:\n"
echo "totle_time: "$total_time" us"
echo "total_exit_time: "$total_exit_time" us"
echo "max_exit_time: "$max_exit_time" us"
echo "max_exit_line_num: "$max_exit_line_num
